package com.xiaoma.guicedemo.demo;

import com.google.inject.*;

import javax.inject.Inject;
import javax.inject.Qualifier;
import java.lang.annotation.Retention;

import static java.lang.annotation.RetentionPolicy.RUNTIME;

/**
 * @author maj
 * @ClassName GuiceDemo
 * @Description
 * @date 2020-04-29 14:08
 */
public class GuiceDemo {
    @Qualifier
    @Retention(RUNTIME)
    @interface Message {}

    @Qualifier
    @Retention(RUNTIME)
    @interface Count {}

    /**
     * Guice module that provides bindings for message and count used in
     * {@link Greeter}.
     */
    static class DemoModule extends AbstractModule {

        @Override
        protected void configure() {
            bind(Key.get(String.class, Message.class)).toInstance("hello world");
        }

        @Provides
        @Count
        static Integer provideCount() {
            return 3;
        }
    }

    static class MyModule extends AbstractModule {

        @Override
        protected void configure() {
//            bind(Key.get(String.class, Message.class)).toInstance("hello world");
        }

        @Provides
        @Singleton
        public Demo getCommunicator() {
            return new Demo("aaa");
        }
    }

    static  class Demo{
        private String name;
        private int age;

        public Demo(String name) {
            this.name = name;
        }

        public void test()
        {
            System.out.println("test.....");
        }
    }

    static class Greeter {
        private final String message;
        private final int count;

        // Greeter declares that it needs a string message and an integer
        // representing the number of time the message to be printed.
        // The @Inject annotation marks this constructor as eligible to be used by
        // Guice.
        @Inject
        Greeter(@Message String message, @Count int count) {
            this.message = message;
            this.count = count;
        }

        void sayHello() {
            for (int i=0; i < count; i++) {
                System.out.println(message);
            }
        }
    }

    public static void main(String[] args) {
        /*
         * Guice.createInjector() takes one or more modules, and returns a new Injector
         * instance. Most applications will call this method exactly once, in their
         * main() method.
         */
        Injector injector = Guice.createInjector(new DemoModule(),new MyModule());

        /*
         * Now that we've got the injector, we can build objects.
         */
        Greeter greeter = injector.getInstance(Greeter.class);

        Demo demo = injector.getInstance(Demo.class);
        demo.test();

        // Prints "hello world" 3 times to the console.
        greeter.sayHello();
    }
}
